package problem92;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

//92.反转链表
    //https://leetcode.cn/problems/reverse-linked-list-ii/
class Solution {
    public ListNode reverseBetween(ListNode head, int l, int r) {
        ListNode newHead = new ListNode();
        newHead.next = head;
        ListNode cur = newHead;
        ListNode left = newHead, right = newHead;
        for(int i = 0; i<l; i++) {
            cur = left;
            left = left.next;
        }
        for(int i = 0; i<r; i++) {
            right = right.next;
        }
        ListNode tmpHead = cur, target = right.next;
        cur = cur.next;
        while(cur != target) {
            ListNode next = cur.next;
            cur.next = tmpHead.next;
            tmpHead.next = cur;
            cur = next;
        }
        left.next = cur;
        return newHead.next;
    }
}